package work;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/servlet3")
//下载数据
public class servlet3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        知道对应的资源
//        获取请求参数
        String name = req.getParameter("name");
//        获取域对象
        ServletContext context = getServletContext();
        String realPath = context.getRealPath("source/" + name);
//        输入流
        FileInputStream fis = new FileInputStream(realPath);
//        输出流
        ServletOutputStream os = resp.getOutputStream();
//        要告诉浏览器数据要以下载的方式接受:
        resp.setHeader("content-disposition" , "attachment;filename="+name);
//        循环读写
        byte[] bytes = new byte[1024];
        int len;
        while((len=fis.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        fis.close();
        os.close();
    }
}

